import Login from './login'

const defaultParam = {
  // baseUrl: 'http://wdtmtest.banajava.com',
  // baseUrl: 'https://wdtmtest.banajava.com',
  // baseUrl: 'http://wdttest.banajava.com',
  // baseUrl: 'http://dev.banajava.com',
  // baseUrl: 'https://wdt.sdqyly.cn',
  // baseUrl: 'https://www.hongfanchi.com.cn',
  baseUrl: 'https://www.xhadujia.com',
  rootPath: '/api/',
  // 若需要cms的namespace，则发版时置为true，否则置为false
  needNamespace: false,
  defaultSuccess(res, cb, notShowError) {
    wx.hideLoading()
    if (!notShowError && res.data && res.data.resultCode !== '200' && res.data.message) {
      wx.showModal({
        content: '[' + res.data.resultCode + ']' + res.data.message,
        showCancel: false
      })
    }
    return typeof cb === 'function' && cb(res)
  },
  fail(ex) {
    console.warn('访问接口数据异常', ex)
    wx.hideLoading()
    wx.showModal({
      title: '网络错误',
      content: '网络出错，请刷新重试',
      showCancel: false
    })
  }
}

const cacheKeyName = 'wdtMiniAppCachHttp'

const encodeId = function (id) {
  if (id) {
    return id.replace(/_/g, '!')
  }
  return id
}

// 批量清除缓存数据
const batchRemoveStore = () => {
  const {keys} = wx.getStorageInfoSync()
  if (keys && keys.length) {
    keys.forEach(key => {
      if (key.indexOf(`${cacheKeyName}_`) === 0) {
        console.log('清除接口缓存数据', key)
        wx.removeStorageSync(key)
      }
    })
  }
}

const $http = (requestParam, config = {}) => {
  if (config.showLoading) {
    wx.showLoading({
      title: '加载中',
    })
  }
  const params = Object.assign({}, defaultParam, requestParam)

  // 设置默认的header，增加token字段
  const result = Login.getFromLocal()
  if (!params.header) {
    params.header = {}
  }
  if (result) {
    // result
    console.log('wxrequest token', result.token)
    if (params.url !== 'miniLogin' && result.token) {
      params.header.Authorization = result.token
    }
  }

  params.success = (res) => {
    if (config.storageCache) {
      const storData = {
        time: new Date().getTime(),
        resultData: res
      }
      let id = requestParam.url
      if (requestParam.data) {
        id += JSON.stringify(requestParam.data)
      }
      const storeKey = `${cacheKeyName}_${encodeId(id)}`
      console.log('接口数据放入缓存中', storeKey, storData)
      wx.setStorageSync(storeKey, storData)
    }
    defaultParam.defaultSuccess(res, requestParam.success, config.notShowError)
  }
  params.url = params.baseUrl + params.rootPath + params.url
  if ((params.config && params.config.needNamespace) || config.needNamespace || params.needNamespace) {
    getNamespace().then(res => {
      params.header['Cms-V2-Namespace'] = res
      wx.request(params)
    })
  } else {
    wx.request(params)
  }
}

const $catchHttp = (requestParam, config = {}) => {
  let id = requestParam.url
  if (requestParam.data) {
    id += JSON.stringify(requestParam.data)
  }
  const storeKey = `${cacheKeyName}_${encodeId(id)}`
  if (config.storageFresh) {
    // 清除缓存数据
    batchRemoveStore()
    // 网络请求
    $http(requestParam, config)
    return
  }
  try {
    const resData = wx.getStorageSync(storeKey)
    console.log('从缓存中得到接口数据', storeKey, resData)
    if (resData) {
      const res = resData.resultData
      // 若数据缓存超过1天，则强制删除
      if (resData.time && new Date().getTime() - resData.time > 1000 * 3600 * 24) {
        batchRemoveStore()
      } else {
        defaultParam.defaultSuccess(res, requestParam.success, config.notShowError)
        return
      }
    }
    wx.hideLoading()
  } catch (e) {
    console.log('获取接口缓存数据异常', e)
    wx.hideLoading()
  }
  // 网络请求
  $http(requestParam, config)
}

const $promiseHttp = (type, url, data, config = {}) => new Promise((resolve, reject) => {
  const requestParam = {
    url,
    success(res) { // 服务器返回数据
      if (res.data.resultCode === '200') { // res.data 为 后台返回数据，
        resolve(res.data)
      } else { // 返回错误提示信息
        reject(res.data)
      }
    },
    error(e) {
      reject(new Error(e.message))
    }
  }
  if (type === 'POST') {
    requestParam.method = 'POST'
    requestParam.data = data
  }

  if (config.storageCache) {
    // 缓存请求
    $catchHttp(requestParam, config)
  } else {
    // 网络请求
    $http(requestParam, config)
  }
})

const httpPost = (requestParam, data, config = {showLoading: true}) => {
  if (typeof requestParam === 'object') {
    requestParam.method = 'POST'
    return requestParam.config && requestParam.config.storageCache
      ? $catchHttp(requestParam, requestParam.config) : $http(requestParam, requestParam.config)
  } else if (typeof requestParam === 'string') {
    return $promiseHttp('POST', requestParam, data, config)
  } else {
    return null
  }
}

const httpGet = (requestParam, config = {showLoading: true}) => {
  if (typeof requestParam === 'object') {
    return requestParam.config && requestParam.config.storageCache
      ? $catchHttp(requestParam, requestParam.config) : $http(requestParam, config)
  } else if (typeof requestParam === 'string') {
    return $promiseHttp('GET', requestParam, null, config)
  } else {
    return null
  }
}

const getNamespace = function () {
  return new Promise((resolve) => {
    const storeKey = `namespace_code_${defaultParam.baseUrl}`
    const resData = wx.getStorageSync(storeKey)
    console.log('从缓存中得到namespace', storeKey, resData)
    if (resData) {
      const res = resData.resultData
      // 若数据缓存超过1天，则强制删除
      if (resData.time && new Date().getTime() - resData.time > 1000 * 3600 * 24) {
        wx.removeStorageSync(resData)
      } else if (res) {
        return resolve(res)
      }
    }
    let domainName = ''
    if (defaultParam.baseUrl.indexOf('https://') > -1) {
      domainName = defaultParam.baseUrl.split('https://')[1]
    } else if (defaultParam.baseUrl.indexOf('http://') > -1) {
      domainName = defaultParam.baseUrl.split('http://')[1]
    }
    wx.request({
      url: `${defaultParam.baseUrl}${defaultParam.rootPath}cmsv2/content/page?namespace=reserved_namespace`,
      data: {
        typeCode: 'website_url_namespace',
        page: 0,
        size: 1,
        otherLikeParam: {
          domain_name: domainName
        }
      },
      method: 'POST',
      success: (res) => {
        const {data} = res
        const {resultCode, resultData} = data
        if (resultCode === '200') {
          const {website_namespace} = resultData && resultData.content && resultData.content.length
            ? resultData.content[0] : {}
          console.log('从接口中得到namespace', website_namespace)
          // 当前namespace存入Storage
          wx.setStorageSync(storeKey, {
            time: new Date().getTime(),
            resultData: website_namespace
          })
          return resolve(website_namespace || '')
        }
      }
    })
  })
}

module.exports = {
  post: httpPost,
  get: httpGet,
  baseUrl: defaultParam.baseUrl
}
